package core.manager
{
import flash.utils.Dictionary;

import mapengine.interfaces.IMapBuilding;

import values.building.BuildingActionValue;

/**
 * BuildingActionManager
 * @author jliang
 *
 */
public class BuildingActionManager
{
	private static var quene:Vector.<BuildingActionValue> = new Vector.<BuildingActionValue>();
	
	public static function addAction(target:IMapBuilding, action:String):void
	{
		var vo:BuildingActionValue = new BuildingActionValue();
		vo.target = target;
		vo.action = action;
		
		if (!isTargetInQuene(target))
		{
			target.enterActionQuene();
		}
		
		quene.push(vo);
		
		if (quene.length == 1)
		{
			startQuene();
		}
	}
	
	public static function isTargetInQuene(target:IMapBuilding):Boolean
	{
		for each (var vo:BuildingActionValue in quene)
		{
			if (vo.target && vo.target.uid == target.uid) return true;
		}		
		return false;
	}
	
	public static function isTargetIsInNextAction(target:IMapBuilding):Boolean
	{
		if (quene.length > 0)
		{
			var vo:BuildingActionValue = quene[0];
			if (vo.target && vo.target.uid == target.uid) return true;
		}
		return false;
	}
	
	public static function getTargetActionQueneCountByAction(target:IMapBuilding, action:String = null):int
	{
		var count:int = 0;
		for (var i:int = 0; i < quene.length; i++)
		{
			var vo:BuildingActionValue = quene[i];
			if (vo.target && vo.target.uid == target.uid)
			{
				if (action && action != "")
				{
					count ++;
				}
				else
				{
					if (action == vo.action)
					{
						count ++;
					}
				}
			}
		}		
		return count;
	}
	
	private static function startQuene():void
	{
		var vo:BuildingActionValue = quene[0];
		
		//如果当前目标的状态的动作与队列动作不符合 或者 当前状态下没有动作定义, 则认为队列中断
		if (!(vo.target.buildingItemValue.currentState.hasAction) || 
			vo.target.buildingItemValue.currentState.actionName != vo.action)
		{
			stopQuene();
			return;
		}
		
		//执行队列
		vo.target.exitActionQuene();
		vo.target.doAction(actionStart, actionComplete);
	}
	
	private static function actionStart(flag:Boolean):void
	{
		if (flag == false)		
		{
			stopQuene();
		}
	}
	
	private static function actionComplete():void
	{
		var vo:BuildingActionValue = quene.shift();
		
		if (isTargetInQuene(vo.target))
		{
			if (!isTargetIsInNextAction(vo.target))
			{
				vo.target.enterActionQuene();
			}
		}
		else
		{
			vo.target.exitActionQuene();		
		}
		
		if (quene.length > 0)
		{
			startQuene();
		}
	}
	
	private static function stopQuene():void
	{
		var dic:Dictionary = new Dictionary(true);
		for each (var vo:BuildingActionValue in quene)
		{
			if (vo.target && dic[vo.target.uid] != true)
			{
				dic[vo.target.uid] = true;
				vo.target.exitActionQuene();
			}
		}		
		dic = null;
	}
}
}




